﻿using HRMSystemShi.DAL;
using HRMSystemShi.Model;

namespace HRMSystemShi._2025
{
    public partial class FormOperatorEdit : Form
    {
        public bool isAdd = false;
        public bool isUpdate = false;
        Operator op = new Operator();
        public FormOperatorEdit()
        {
            InitializeComponent();
            isAdd = true;
        }
        public FormOperatorEdit(Guid id)
        {
            InitializeComponent();
            op = OperatorService.GetOperator(id);
            isUpdate = true;
        }

        private void FormOperatorEdit_Load(object sender, EventArgs e)
        {
            if (isUpdate)
            {
                labelPassword.Hide();
                textBoxPassword.Hide();

                textBoxUserName.Text = op.UserName;
                textBoxRealName.Text = op.RealName;
                checkBoxIsDeleted.Checked = op.IsDeleted;
                checkBoxIsLocked.Checked = op.IsLocked;
                checkBoxIsAdmin.Checked = op.IsAdmin;
            }
            if (isAdd)
            {
                checkBoxResetPassword.Hide();
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (op == null && isUpdate)
            {
                op!.Id = Guid.NewGuid();
            }
            op!.UserName = textBoxUserName.Text.Trim();
            op.Password = CommonHelper.GetMD5(textBoxPassword.Text.Trim());
            op.RealName = textBoxRealName.Text.Trim();
            op.IsDeleted = checkBoxIsDeleted.Checked;
            op.IsLocked = checkBoxIsLocked.Checked;
            op.IsAdmin = checkBoxIsAdmin.Checked;

            if (checkBoxResetPassword.Checked)
            {
                op.Password = CommonHelper.GetMD5("123");
            }
            if (isAdd)
            {
                if (OperatorService.AddOperator(op))
                {
                    CommonHelper.MessageSuccess("保存成功");
                    this.Close();
                }
                else
                {
                    CommonHelper.MessageError("保存失败");
                }
            }
            else if (isUpdate)
            {
                if (OperatorService.UpdateOperator(op))
                {
                    CommonHelper.MessageSuccess("修改成功");
                    this.Close();
                }
                else
                {
                    CommonHelper.MessageError("修改失败");
                }
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            if(CommonHelper.MessageYesOrNo("确定取消吗?") == DialogResult.Yes)
            {
                this.Close();
            }
        }
    }
}
